package ui.search

import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import model.dto.AddFriendDTO
import model.enums.NetworkSate
import model.repository.ChannelMappingRepository
import model.vo.SearchedItem
import state.ApplicationWindowsState


/**
 * @author wei kunJie
 * @date 2024/4/13 14:04:36
 */
class SearchViewModel(
    val applicationWindowsState: ApplicationWindowsState,
    private val coroutineScope: CoroutineScope
) {
    val searchText = mutableStateOf("")//搜索关键字
    val searchedItems = mutableStateListOf<SearchedItem>()//搜索出来的item
    val networkState = mutableStateOf(NetworkSate.watting)//网络请求结果状态
    val networkRMsg = mutableStateOf("")//网络请求后给用户的提示msg
    val authenticationInformation = mutableStateOf("")//验证信息
    val addUserAccount = mutableStateOf("")//要添加的用户账号
    val searchBtnEnabled = mutableStateOf(true)//要添加的用户账号

    init {

    }

    fun addFriend() {
        //开启一个协程，并指定在IO调度器上执行
        coroutineScope.launch(Dispatchers.IO) {
            val addFriendDTO = AddFriendDTO(authenticationInformation.value, addUserAccount.value)
            ChannelMappingRepository.addFriendApply(addFriendDTO, networkState, networkRMsg)
        }
    }

    fun searchChannelMapping() {
        if (searchText.value.isEmpty()) return
        searchBtnEnabled.value=false
        coroutineScope.launch(Dispatchers.IO) {
            ChannelMappingRepository.searchChannelMapping(searchText.value, searchedItems,searchBtnEnabled)
        }
    }

    fun isFriend(item: SearchedItem): Boolean {
        return ChannelMappingRepository.channelMappingAccountList.contains(item.userAccountOrGroupAccount)
    }
}